package com.stuffthathappens.concurrency;

import java.util.concurrent.TimeUnit;

/**
 * This little program demonstrates that when all non-daemon threads
 * complete, the VM exits. When the VM exits, it does NOT execute
 * code inside of daemon thread finally blocks. These threads "just die"
 * without any opportunity to clean up.
 */
public class DaemonExitDemo {
    public static void main(String[] args) {
        new MyThread("A", true, 3).start();

        // the VM exits when this thread completes, WITHOUT executing
        // the code in the daemon thread's finally block
        new MyThread("B", false, 1).start();
    }

    static class MyThread extends Thread {
        private final int delay;
        public MyThread(String name, boolean daemon, int delay) {
            super(name);
            this.delay = delay;
            setDaemon(daemon);
        }

        public void run() {
            String id = String.format("Thread %s (daemon=%b)",
                    getName(), isDaemon());
            try {
                System.out.format("%s started, sleeping %d seconds.%n",
                        id, delay);
                TimeUnit.SECONDS.sleep(delay);
            } catch (InterruptedException ie) {
                System.out.format("%s interrupted.%n", id);
            } finally {
                System.out.format("%s finally.%n", id);
            }
        }
    }
}
